<?php
/*******************************************************************************

    FinalsClub.org is a platform for students and faculty to collaborate
    and share their knowledge with the world.

    Copyright (C) 2009  Andrew Magliozzi

    This file is a part of FinalsClub.org.

    FinalsClub.org is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    To contact FinalsClub.org, send an email to info@finalsclub.org, or
    send mail to Finals Club, c/o Veritas Tutors, 1132 Massachusetts Avenue,
    Cambridge, MA 02138.

*******************************************************************************/

/**
 * group_members actions.
 *
 * @package    FinalsClub
 * @subpackage group_members
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class group_membersActions extends sfActions {
	
	public function executeCreate(sfWebRequest $request) {
		$group_id = $request->getParameter('group_id', 'No valid group_id was found in the request.');
		$this->forward404Unless($group_id);
		// make sure this user is not already a member of the group
		$groupMember = GroupMemberPeer::retrieveByUserIdAndGroupId($this->getUser()->getId(), $group_id);
		if($groupMember) {
			$this->getUser()->setFlash('error', 'You are already a member of this group.');	
		} else {
			$groupMember = new GroupMember();
			$groupMember->setGroupId($group_id);
			$groupMember->setUserId($this->getUser()->getId());
			$groupMember->setRole(GroupMemberPeer::CONTRIBUTOR);
			$groupMember->setStatus(GroupMemberPeer::PENDING_STATUS);
			$groupMember->save();
			
			/* we want to send an e-mail alert to the group admins so next we
			 create an array of the e-mail addresses to send the alert to
			*/
			$user = new User();
			$members = new GroupMember();
			$members = GroupMemberPeer::retrieveByGroupId($group_id);
			foreach($members as $member) {
				if(intval($member->getRole()) == GroupMemberPeer::ADMIN) {
					$user = UserPeer::retrieveById($member->getUserId());
					$admin_emails[] = $user->getEmail();
				}
			}
			
			// we need the group name for the e-mail
			$group = new Group();
			$group = GroupPeer::retrieveById($group_id);
			$group_name = $group->getName();
			
			// we also need the url to approve/reject the membership : groups/edit/id/[group_id]
			$url = $this->generateUrl('default', array('module'=>'groups', 'action'=>'show', 'id'=>$group_id), true);
			
		    // retrieve the smtp server from the app.yml
			$smtp_server = sfConfig::get('app_smtp_server');
			$smtp_user = sfConfig::get('app_smtp_user');
			$smtp_password = sfConfig::get('app_smtp_password');
			try
			{
			  // Create the mailer
			  $connection = new Swift_Connection_SMTP($smtp_server, 465, Swift_Connection_SMTP::ENC_SSL);
			  $connection->setUsername($smtp_user);
			  $connection->setPassword($smtp_password);
			  $mailer = new Swift($connection);  
			  
			  // Subject line
			  $message = new Swift_Message('FinalsClub Group Membership Request');
			 
			  // Setup our list of recipients (group admins)
			  $recipients = new Swift_RecipientList();
			  foreach($admin_emails as $address) {
			  	$recipients->addTo($address);
			  }
			  
			  // Render message parts
			  $mailContext = array('group_name'=>$group_name,'url'=>$url);	// to be passed as parameters to the partials
			  $message->attach(new Swift_Message_Part($this->getPartial('membershipRequestHtml', $mailContext), 'text/html'));		// HTML e-mail body
			  $message->attach(new Swift_Message_Part($this->getPartial('membershipRequestPlain', $mailContext), 'text/plain'));	// Plaintext e-mail body
			 
			  // Set the 'To' and 'From' fields. To will be our recipient list which is an array of admin e-mail addresses
			  // batchSend sends to an array of addresses
			  $mailer->batchSend($message, $recipients, $smtp_user);
			  $mailer->disconnect();
			}
			catch (Exception $e)
			{
			  	$this->logMessage($e->getMessage(), 'crit');	// Log the exception as critical
			  	$this->getUser()->setFlash('warning', 'Failed to initialize mailer!');		// alert the user e-mailing failed
			}
		}
		$this->groupMember = $groupMember;
		$request->setParameter('id', $group_id);
		$this->forward('groups', 'show');
	}
	
	/**
	 * Removes a user from a group
	 * @param $request
	 * @return forwards to group edit module
	 */
	public function executeDestroy(sfWebRequest $request) {
		$this->forward404Unless($request->getParameter('id'), 'No valid id was found in the request.');
		$groupMember = GroupMemberPeer::retrieveById($request->getParameter('id'));
		$this->forward404Unless($groupMember, 'The group membership was not found.');
		
		// make sure the user is not trying to delete their own account
		if($groupMember->getUserId() == $this->getUser()->getId()) {
			$this->getUser()->setFlash('error', 'You cannot delete your own account.');
		} else if(!$this->getUser()->isGroupAdmin($groupMember->getGroupId())) { // make sure the user has admin permissions to delete the user 
			$this->getUser()->setFlash('error', 'You must be an administrator of this group to remove members.');
		} else {
			$this->getUser()->setFlash('success', 'You have successfully deleted '.$groupMember->getUser()->getFullName().' from your group.');
			$groupMember->delete();
		}
		
		$request->setParameter('id', $groupMember->getGroupId());
		$this->forward('groups', 'edit');
	}
	
	public function executeUpdate(sfWebRequest $request) {
		$this->forward404Unless($request->getParameter('id'));
		$groupMember = GroupMemberPeer::retrieveById($request->getParameter('id'));
		
		$this->forward404Unless($groupMember, 'The group membership was not found');
		// make sure the current user is an admin
		if($this->getUser()->isGroupAdmin($groupMember->getGroupId())) {
			$status = $request->getParameter('status', 0);
			$groupMember->setStatus($status);
			$groupMember->save();
			
			if($status == GroupMemberPeer::APPROVED_STATUS) {
				$this->getUser()->setFlash('success', 'You have successfully added '. $groupMember->getUser()->getFullName() .' to your group.');

				// send the user an e-mail alert to let them know
				// their membership was approved, we need the group name, user's name and email
				$group = new Group();
				$group = GroupPeer::retrieveById($groupMember->getGroupId());
				$group_name = $group->getName();
				
				$user = new User();
				$user = UserPeer::retrieveById($groupMember->getUserId());
				$name = $user->getFullName();
				$to = $user->getEmail();
				
				// we also need the url to view the group : groups/show/id/[group_id]
				$url = $this->generateUrl('default', array('module'=>'groups', 'action'=>'show', 'id'=>$group->getId()), true);
				
			    // retrieve the smtp server from the app.yml
				$smtp_server = sfConfig::get('app_smtp_server');
				$smtp_user = sfConfig::get('app_smtp_user');
				$smtp_password = sfConfig::get('app_smtp_password');
				try
				{
				  // Create the mailer
				  $connection = new Swift_Connection_SMTP($smtp_server, 465, Swift_Connection_SMTP::ENC_SSL);
				  $connection->setUsername($smtp_user);
				  $connection->setPassword($smtp_password);
				  $mailer = new Swift($connection);  
				  
				  // Subject line
				  $message = new Swift_Message('FinalsClub Group Membership Request Status');
				  
				  // Render message parts
				  $mailContext = array('name'=>$name, 'group_name'=>$group_name, 'url'=>$url);	// to be passed as parameters to the partials
				  $message->attach(new Swift_Message_Part($this->getPartial('membershipAcceptedHtml', $mailContext), 'text/html'));		// HTML e-mail body
				  $message->attach(new Swift_Message_Part($this->getPartial('membershipAcceptedPlain', $mailContext), 'text/plain'));	// Plaintext e-mail body
				 
				  // Set the 'To' and 'From' fields.
				  $mailer->send($message, $to, $smtp_user);
				  $mailer->disconnect();
				}
				catch (Exception $e)
				{
				  	$this->logMessage($e->getMessage(), 'crit');	// Log the exception as critical
				  	$this->getUser()->setFlash('warning', 'Failed to initialize mailer!');		// alert the user e-mailing failed
				}
				
			} else {
				$this->getUser()->setFlash('notice', 'You have successfully declined '. $groupMember->getUser()->getFullName() .' from your group.');
			}
		} else {
			$this->getUser()->setFlash('error', 'You must be an administrator of this group to approve members.');
		}
		
		$request->setParameter('id', $groupMember->getGroupId());
		$this->forward('groups', 'show');
	}

}
